#include <ctype.h>

#include "util.h"

static unsigned char hexchars[] = "0123456789ABCDEF";

static int htoi(char* s)
{
    int value;
    int c;

    c = s[0];
    if (isupper(c)) {
        c = tolower(c);
    }

    value = c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10;
    value <<= 4;

    c = s[1];
    if (isupper(c)) {
        c = tolower(c);
    }

    value += c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10;

    return value;
}

int url_decode(char* str, int len)
{
    char* dest = str;
    char* data = str;

    while (len--) {
        if (*data == '+') {
            *dest = ' ';
        } else if (*data == '%' && len >= 2 && isxdigit(*(data + 1)) && isxdigit(*(data + 2))) {
            *dest = htoi(data + 1);
            data += 2;
            len -= 2;
        } else {
            *dest = *data;
        }
        data++;
        dest++;
    }
    *dest = '\0';
    return dest - str;
}
